import Vue from 'vue'
import VueRouter from 'vue-router'

//引入登录组件
import Login from '../pages/Login'
import Home from '../pages/Home'
import Welcome from '../pages/Welcome'
import Users from '../components/user/Users'
import Rights from '../components/power/Rights'
import Roles from '../components/power/Roles'
import Cate from '../components/goods/Cate'
import Params from '../components/goods/Params'
import GoodsList from '../components/goods/GoodsList'
import Add from '../components/goods/Add'
import Order from '../components/order/Order'
import Report from '../components/Report'
import NotFound from '../components/NotFound'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    //当访问主页面时重定向到登录页面
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: Users
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component: Roles
      },
      {
        path: '/categories',
        component: Cate
      },
      {
        path: '/params',
        component: Params
      },
      {
        path: '/goods',
        component: GoodsList,
      },
      {
        path: '/goods/add',
        component: Add,
      },
      {
        path: '/orders',
        component: Order,
      },
      {
        path: '/reports',
        component: Report,
      }, 
      {
        path: '/notFound',
        component: NotFound,
      }
    ]
  },

]

const router = new VueRouter({
  routes
})

//挂载路由导航
router.beforeEach((to, from, next) => {
  //将要访问的路径  --to
  //从哪个路径跳转而来  --from
  //一个函数，表示放行  --next  1.next()直接放行  2.next('/...')强制跳转路径
  if (to.path === '/login') return next()   //如果访问登陆页面，直接放行
  //获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('login')   //如果token为空 强制跳转到登陆页面
  next()  //token存在放行 
})

export default router
